package com.neo.common.base;

import com.neo.config.exception.BasicException;
import com.neo.config.exception.BusinessException;
import com.neo.config.exception.ExceptionEntity;

import com.neo.config.exception.ParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 */
public class BaseController {

    /**
     * 指定异常全局处理
     *
     * @param request
     * @param response
     * @param exception
     * @return
     */

    @ExceptionHandler(value = BasicException.class)
    public ExceptionEntity errorHandler(HttpServletRequest request, HttpServletResponse response, BasicException
            exception) {
        ExceptionEntity entity = new ExceptionEntity();
        entity.setMessage(exception.getMessage());
        entity.setPath(request.getRequestURI());
        entity.setError(exception.getClass().getSimpleName());
        int code = 500;
        if (exception instanceof ParameterException) {
            code = 400;
        }
        if (exception instanceof BusinessException) {
            code = 501;
        }
        response.setStatus(code);
        return entity;

    }

    protected String sucess() {
        return ReturnJson.jsonString("成功", AppConstants.OK);
    }

    protected String sucess(Object data) {
        return ReturnJson.jsonString("成功", data, AppConstants.OK);
    }

    protected String fail() {
        return ReturnJson.jsonString("失败", AppConstants.FAIL);
    }

    /**
     * 自定义失败消息
     *
     * @param message
     * @return
     */
    protected String fail(String message) {
        return ReturnJson.jsonString(message, AppConstants.FAIL);
    }

    /**
     * 自定义失败状态
     *
     * @param status
     * @return
     */
    protected String fail(int status) {
        return ReturnJson.jsonString("失败", status);
    }

    /**
     * 自定义失败状态，失败消息
     *
     * @param status
     * @param message
     * @return
     */
    protected String fail(int status, String message) {
        return ReturnJson.jsonString(message, status);
    }

}
